package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.exception.orderInfo.OrderInfoException;
import com.woniu.exception.venueAdmin.VenueAdminException;
import com.woniu.model.Result;
import com.woniu.product.client.AccountClient;
import com.woniu.product.client.VenueClient;
import com.woniu.product.client.model.Coach;
import com.woniu.product.client.model.VenueAdminDto;
import com.woniu.product.client.model.VenueClassroom;
import com.woniu.product.client.model.VenueInfo;
import com.woniu.product.dto.ClassDto;
import com.woniu.product.dto.VenueClassDto;
import com.woniu.product.form.venueClass.LoadVenueClassByConditionForm;
import com.woniu.product.model.Class;
import com.woniu.product.dao.ClassDao;
import com.woniu.product.param.*;
import com.woniu.product.param.venueClass.LoadVenueClassParam;
import com.woniu.product.service.ClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.StateUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@Service
public class ClassServiceImpl extends ServiceImpl<ClassDao, Class> implements ClassService {
    @Resource
    private AccountClient accountClient;
    @Resource
    private VenueClient venueClient;

    @Resource
    private ClassDao classDao;

    /**
     *根据id查询团课信息
     * @param id 团课id
     * @return
     * @throws Exception
     */
    @Override
    public Class ByIdClass(Integer id) throws Exception {
        QueryWrapper<Class> classQueryWrapper = new QueryWrapper<>();
        classQueryWrapper.eq("class_id",id);
        classQueryWrapper.eq("class_type",1);
        Class aClass = classDao.selectOne(classQueryWrapper);
        if(aClass==null||aClass.getClassState()==2){
            throw new OrderInfoException(500,"团课不存在");
        }
        return aClass;
    }


        /**
         * 新增团课
         * @param param
         * @throws Exception
         */
        @Override
        @GlobalTransactional(rollbackFor = Throwable.class)
        public void addClass(AddClassParam param) throws Exception {
            Result<VenueAdminDto> coachResult = accountClient.getVenueCoachBtId(param.getCoachId());
//            Result<Coach> coachId = (Result<Coach>) venueCoachBtId;
            if (coachResult.getCode()!=200){
                throw new VenueAdminException(coachResult.getCode(),coachResult.getMsg());
            }
            if (ObjectUtil.isEmpty(coachResult.getData())) {
                throw new VenueAdminException(500, "教练不存在");
            }
            Result<VenueInfo> venueId = venueClient.loadVenueInfoById(param.getVenueId());
            if (venueId.getCode()!=200){
                throw new VenueAdminException(venueId.getCode(), venueId.getMsg());
            }
            if (ObjectUtil.isEmpty(venueId.getData())){
                throw new VenueAdminException(500,"场馆不存在");
            }
            if (param.getPrice().compareTo(BigDecimal.ZERO)<=0){
                throw new VenueAdminException(500,"价格错误");
            }

            Result<VenueClassroom> venueRoom = venueClient.loadVenueRoom(param.getClassroomId());
            VenueClassroom roomData = venueRoom.getData();
            if (param.getClassType()==1&&param.getPeopleNum()>roomData.getPeopleNum()){
                throw new VenueAdminException(500,"人数大于教室上限");
            }
//            Class aClass = new Class();
//            aClass.setClassName(param.getClassName());
//            aClass.setClassDetail(param.getClassDetail());
//            aClass.setVenueId(param.getVenueId());
//            aClass.setMinute(param.getMinute());
//            aClass.setClassState(1);
//            aClass.setCoachId(param.getCoachId());
//            aClass.setMemberPrice(param.getPrice());
//            aClass.setPeopleNum(param.getPeopleNum());
//            aClass.setClassroomId(param.getClassroomId());
//            aClass.setClassType(1);
            Class aClass = BeanUtil.toBean(param, Class.class);
            classDao.insert(aClass);

        }

    /**
     * 删除团课
     * @param classId 团课id
     * @throws Exception
     */
    @Override
    public void delClass(Integer classId) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_id",classId);
        wrapper.eq("class_type",1);
        Class aClass = classDao.selectOne(wrapper);
        if (aClass==null){
            throw new OrderInfoException(500,"团课id不存在或不是团课");
        }
        aClass.setClassState(0);
        classDao.updateById(aClass);
    }

    /**
     * 团课上架
     * @param classId 团课id
     * @param venueId 场馆id
     * @throws Exception
     */
    @Override
    public void putawayClass(Integer classId, Integer venueId) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_id",classId);
        Class aClass = classDao.selectOne(wrapper);
        if (!aClass.getVenueId().equals(venueId)){
            throw new OrderInfoException(500,"场馆无权限");
        }
        //修改团课状态为0,可预约团课
        aClass.setClassState(0);
        classDao.updateById(aClass);
    }

    /**
     * 根据团课名查询所有团课对象
     * @param className
     * @param classType
     * @return
     * @throws Exception
     */
    @Override
    public List<Class> loadAllClass(String className,Integer classType) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_name",className);
        wrapper.eq("class_type",1);
        List<Class> classes = classDao.selectList(wrapper);
        return classes;
    }

    /**
     * 修改团课状态为已完课
     * @param param
     * @throws Exception
     */
    @Override
    public void updateClassState(UpdateClassStateParam param) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_type",1);
        Class aClass = classDao.selectById(wrapper);
        if (aClass==null){
            throw new OrderInfoException(500,"团课不存在");
        }
        if (aClass.getClassState().equals(param.getClassState())){
            throw new OrderInfoException(500,"团课状态已是完课状态");
        }
        aClass.setClassState(3);
        classDao.updateById(aClass);
    }

    @Override
    public void addPersonal(AddPersonalParam param) throws Exception {
        Result<Coach> coachId = accountClient.byId(param.getCoachId());
        if (coachId==null){
            throw new VenueAdminException(500,"教练不存在");
        }
        Result<VenueInfo> venueId = venueClient.loadVenueInfoById(param.getVenueId());
        if (venueId==null){
            throw new VenueAdminException(500,"场馆不存在");
        }


        if (param.getPrice().compareTo(BigDecimal.ZERO)<=0){
            throw new VenueAdminException(500,"价格错误");
        }


        Class aClass = new Class();
        aClass.setClassName(param.getClassName());
        aClass.setClassDetail(param.getClassDetail());
        aClass.setVenueId(param.getVenueId());
        aClass.setMinute(param.getMinute());
        aClass.setClassState(1);
        aClass.setCoachId(param.getCoachId());
        aClass.setMemberPrice(param.getPrice());
        aClass.setClassroomId(param.getClassRoomId());
        aClass.setClassType(2);
        classDao.insert(aClass);



    }

    @Override
    public void delPersonal(Integer classId) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_id",classId);
        wrapper.eq("class_type",2);
        Class aClass = classDao.selectOne(wrapper);
        if (aClass==null){
            throw new OrderInfoException(500,"私教课不存在");
        }
        aClass.setClassState(0);
        classDao.updateById(aClass);
    }

    /**
     * 通过教练id查询该教练团课
     * @param coachId 教练id
     * @return
     * @throws Exception
     */

    @Override
    public List coachByIdClass(Integer coachId) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id",coachId);
        wrapper.eq("class_type",1);
        List<Class> classes = classDao.selectList(wrapper);
        if (classes==null){
            throw new OrderInfoException(500,"该教练没有团课");
        }
        return classes;
    }

    /**
     *通过场馆id查询该场馆团课
     * @param venueId
     * @return
     * @throws Exception
     */

    @Override
    public List venueByIdClass(Integer venueId) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("venue_id",venueId);
        List<Class> classes = classDao.selectList(wrapper);
        if (classes==null){
            throw new OrderInfoException(500,"该场馆没有团课");
        }


        return classes;
    }

    /**
     * 教练分页查询所有团课
     * @param param
     * @return
     * @throws Exception
     */

    @Override
    public PageInfo<ClassDto> pageAllClass(PageCoachClassParam param) throws Exception {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }

        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.ne("class_state", 0);
        wrapper.eq("coach_id", param.getCoachId());
        wrapper.eq("class_type",1);
        Page<Class> classPage = classDao.selectPage(new Page<Class>(param.getPageNum(), param.getPageSize()), wrapper);

        List<ClassDto> classDtos = new ArrayList<>();
        for (Class leagueClass : classPage.getRecords()) {
            ClassDto pageDto = BeanUtil.toBean(leagueClass, ClassDto.class);

            //通过教练ID查出教练名字赋值给dto
            String coachName = accountClient.byId(leagueClass.getCoachId()).getData().getCoachName();
            if (coachName == null) {
                throw new OrderInfoException(500, "请先招募教练");
            }
            pageDto.setCoachName(coachName);

            //通过场馆ID查出场馆名字
            String venueName = venueClient.loadVenueInfoById(leagueClass.getVenueId()).getData().getVenueName();
            if (venueName == null) {
                throw new OrderInfoException(500, "场馆不存在");
            }
            pageDto.setVenueName(venueName);

            classDtos.add(pageDto);
        }


        // 计算 startRow 和 endRow
        long startRow = (long) (param.getPageNum() - 1) * param.getPageSize() + 1;
        long endRow = startRow + classDtos.size() - 1;

        // 创建 PageInfo 对象
        PageInfo<ClassDto> pageInfo = new PageInfo<>(classDtos);
        pageInfo.setPageNum(param.getPageNum());
        pageInfo.setPageSize(param.getPageSize());
        pageInfo.setTotal(classPage.getTotal());
        pageInfo.setPages((int) classPage.getPages());
        pageInfo.setSize(classDtos.size());
        pageInfo.setStartRow(startRow);
        pageInfo.setEndRow(endRow);

        return pageInfo;

//        if (param.getPageNum() == null) {
//            param.setPageNum(1);
//        }
//
//        if (param.getPageSize() == null) {
//            param.setPageSize(5);
//        }
//        QueryWrapper<Class> wrapper = new QueryWrapper<>();
//        wrapper.ne("class_state",0);
//        wrapper.eq("coach_id",param.getCoachId());
//        Page<Class> classPage = classDao.selectPage(new Page<Class>(param.getPageNum(), param.getPageSize()), wrapper);
//        Page<ClassDto> classDtoPage = new Page<>();
//        Page<ClassDto> page = new Page<>();
//        page.setCurrent(classPage.getCurrent());
//        page.setOptimizeCountSql(classPage.optimizeCountSql());
//        page.setPages(classPage.getPages());
//        page.setSearchCount(classPage.searchCount());
//        page.setSize(classPage.getSize());
//        page.setTotal(classPage.getTotal());
//
//        ArrayList<ClassDto> classDtos = new ArrayList<>();
//
//
//        for (Class leagueClass:classPage.getRecords()){
//            ClassDto pageDto = BeanUtil.toBean(leagueClass, ClassDto.class);
//
//            //通过教练ID查出教练名字赋值给dto
//            String coachName = accountClient.byId(leagueClass.getCoachId()).getData().getCoachName();
//            if (coachName == null){
//                throw new OrderInfoException(500,"请先招募教练");
//            }
//            pageDto.setCoachName(coachName);
//
//            //通过场馆ID查出场馆名字
//            String venueName = accountClient.venueById(leagueClass.getVenueId()).getData().getVenueName();
//            if (venueName == null){
//                throw new OrderInfoException(500,"场馆不存在");
//            }
//            pageDto.setVenueName(venueName);
//
//            classDtos.add(pageDto);
//        }
//                 page.setRecords(classDtos);
//                   return page;
    }

    /**
     * 查询团课集合
     * @return
     * @throws Exception
     */
    @Override
    public List loadListClass() throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_type",1);
        wrapper.ne("class_state",0);
        List<Class> classes = classDao.selectList(wrapper);
        return classes;
    }

    @Override
    public List loadListPersonal() throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_type",2);
        wrapper.ne("class_state",0);
        List<Class> classes = classDao.selectList(wrapper);
        return classes;

    }

    /**
     *  场馆分页查询团课
     * @param param
     * @return
     * @throws Exception
     */

    @Override
    public PageInfo<VenueClassDto> pageAllVenueClass(PageAllVenueClassParam param) throws Exception {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }

        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.ne("class_state", 0);
        wrapper.eq("coach_id", param.getVenueId());
        wrapper.eq("class_type",1);
        Page<Class> classPage = classDao.selectPage(new Page<Class>(param.getPageNum(), param.getPageSize()), wrapper);

        List<VenueClassDto> classDtos = new ArrayList<>();
        for (Class leagueClass : classPage.getRecords()) {
            VenueClassDto pageDto = BeanUtil.toBean(leagueClass, VenueClassDto.class);

//            //通过教练ID查出教练名字赋值给dto
//            String coachName = accountClient.byId(leagueClass.getCoachId()).getData().getCoachName();
//            if (coachName == null) {
//                throw new OrderInfoException(500, "请先招募教练");
//            }
//            pageDto.setCoachName(coachName);

            //通过场馆ID查出场馆名字
            String venueName = venueClient.loadVenueInfoById(leagueClass.getVenueId()).getData().getVenueName();
            if (venueName == null) {
                throw new OrderInfoException(500, "场馆不存在");
            }
            pageDto.setVenueName(venueName);

            classDtos.add(pageDto);
        }


        // 计算 startRow 和 endRow
        long startRow = (long) (param.getPageNum() - 1) * param.getPageSize() + 1;
        long endRow = startRow + classDtos.size() - 1;

        // 创建 PageInfo 对象
        PageInfo<VenueClassDto> pageInfo = new PageInfo<>(classDtos);
        pageInfo.setPageNum(param.getPageNum());
        pageInfo.setPageSize(param.getPageSize());
        pageInfo.setTotal(classPage.getTotal());
        pageInfo.setPages((int) classPage.getPages());
        pageInfo.setSize(classDtos.size());
        pageInfo.setStartRow(startRow);
        pageInfo.setEndRow(endRow);

        return pageInfo;
    }

    /**
     * 根据教练id查询该教练的私教课程
     * @param coachId
     * @return
     * @throws Exception
     */

    @Override
    public List coachByIdPersonal(Integer coachId) throws Exception {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id",coachId);
        wrapper.eq("class_type",2);
        List<Class> classes = classDao.selectList(wrapper);
        if (classes==null){
            throw new OrderInfoException(500,"该教练没有私教课");
        }
        return classes;
    }

    @Override
    public void updateClassPersonal(UpdateClassPersonalParam param) {
        QueryWrapper<Class> wrapper = new QueryWrapper<>();
        wrapper.eq("class_type",2);
        wrapper.eq("class_id",param.getClassId());
        Class aClass = classDao.selectOne(wrapper);
        if (aClass==null){
            throw new OrderInfoException(500,"私教课不存在");
        }
        if (aClass.getClassState()==1){
            throw new OrderInfoException(500,"该私教课程已是可预约状态");
        }
        aClass.setClassState(1);
        classDao.updateById(aClass);
    }

    @Override
    public PageInfo<VenueClassDto> load(LoadVenueClassParam param) {
        PageHelper.startPage(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 6 : param.getPageSize());
        List<VenueClassDto> venueClassDtos = classDao.load(param);
        PageInfo<VenueClassDto> venueClassDtoPageInfo = new PageInfo<>(venueClassDtos);
        return venueClassDtoPageInfo;
    }

    @Override
    public List<VenueClassDto> loadVenueClassByCondition(LoadVenueClassByConditionForm form) {
        LoadVenueClassParam param = new LoadVenueClassParam();
        param.setVenueId(form.getVenueId());
        param.setClassName(form.getCondition());
        param.setClassState(StateUtil.CLASS_STATE_NOMAL);
        param.setClassType(1);
        List<VenueClassDto> load = classDao.load(param);
        return load;
    }
}
